import type { FC, PropsWithChildren } from 'react';
import { useSetState } from 'ahooks';
import cookie from 'js-cookie';
import React, { useEffect } from 'react';
import Mask from '../Mask';
import Eyes from '../Eyes';
import Loading from '../Loading';
import styles from './index.module.scss';
import { login, register, validResume } from '@/service';
import notification from '@/app/components/hooks/useNotification';
import Confirm from '../Confirm';
import { usePathname } from 'next/navigation';
import { useCommonStore } from '@/src/providers/common-store-provider';

interface IndexProps {
  needReload?: boolean;
}
function FormItem(props) {
  const { label, name, value, onChange, errorMeassage } = props;
  const [state, setState] = useSetState({
    accountFocus: false,
    passwordFocus: false,
    account: '',
    password: '',
    isHidden: true,
    isLogin: true,
  });
  return (
    <div className={styles.formItem}>
      <input
        type={state.isHidden && props.type === 'password' ? 'password' : 'text'}
        id={name}
        value={value}
        onFocus={() => {
          setState({
            accountFocus: true,
          });
        }}
        onBlur={() => {
          setState({
            accountFocus: false,
          });
        }}
        onInput={(e: any) => {
          onChange(e.target.value);
        }}
        style={{ background: '#fff' }}
      />
      <label
        className={state.accountFocus || value ? styles.focus : ''}
        htmlFor={name}
      >
        {label}
      </label>
      {props.type === 'password' ? (
        <Eyes
          isHidden={state.isHidden}
          onChange={(e) => {
            setState({ isHidden: e });
          }}
          style={{ position: 'absolute', right: '10px', bottom: '10px' }}
        ></Eyes>
      ) : null}
      {errorMeassage ? (
        <div className={styles.error}>{errorMeassage}</div>
      ) : null}
    </div>
  );
}

const Index: FC<PropsWithChildren<IndexProps>> = ({ children, needReload }) => {
  const { setShowLogin, setIsLogin } = useCommonStore((state) => state);
  const pathname = usePathname();
  const [state, setState] = useSetState({
    accountError: '',
    passwordError: '',
    account: '',
    password: '',
    isLogin: true,
    loading: false,
    show: true,
  });

  useEffect(() => {
    let user: any = localStorage.getItem('user');
    if (user) {
      user = JSON.parse(user);
      setState({ account: user.account, password: user.password });
    } else {
      setState({
        isLogin: false,
      });
    }
  }, []);
  const validate = (account: string, password: string) => {
    const o = {
      accountError: '',
      passwordError: '',
    };
    if (!account) {
      o.accountError = '请填写用户名';
    }
    if (!password) {
      o.passwordError = '请填写密码';
    }
    if (!state.isLogin && account) {
      const phoneRegex = /^1[3456789]\d{9}$/;
      const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
      if (!phoneRegex.test(account) && !emailRegex.test(account)) {
        o.accountError = '请填写正确的手机号或邮箱';
      }
    }
    if (!state.isLogin && password) {
      if (password.length < 6) {
        o.passwordError = '密码长度不能小于6位';
      }
    }
    setState(o);
    if (o.accountError || o.passwordError) {
      return false;
    }
    return true;
  };
  return (
    <>
      {children}
      {state.show ? (
        <Mask>
          <div className={styles.login}>
            {!needReload ? (
              <div
                className={styles.close}
                onClick={() => {
                  setState({ show: false });
                  setShowLogin(false);
                }}
              >
                <svg
                  viewBox="0 0 1024 1024"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
                  width="24"
                  height="24"
                >
                  <path
                    d="M544.448 499.2l284.576-284.576a32 32 0 0 0-45.248-45.248L499.2 453.952 214.624 169.376a32 32 0 0 0-45.248 45.248l284.576 284.576-284.576 284.576a32 32 0 0 0 45.248 45.248l284.576-284.576 284.576 284.576a31.904 31.904 0 0 0 45.248 0 32 32 0 0 0 0-45.248L544.448 499.2z"
                    fill="#3E3A39"
                  ></path>
                </svg>
              </div>
            ) : null}

            <h2 className={styles.title}>{state.isLogin ? '登录' : '注册'}</h2>
            <div style={{ marginTop: '25px' }}>
              <FormItem
                label={
                  <>
                    <svg
                      viewBox="0 0 1024 1024"
                      version="1.1"
                      xmlns="http://www.w3.org/2000/svg"
                      width="32"
                      height="32"
                    >
                      <path
                        d="M642.8 531.8c64.3-42.6 106.9-115.4 106.9-198.1C749.7 202.6 643.1 96 512 96S274.3 202.6 274.3 333.7c0 82.7 42.6 155.6 106.9 198.1C215.8 582.9 96 727.7 96 898.3c0 16.4 13.3 29.7 29.7 29.7s29.7-13.3 29.7-29.7c0-180.2 159.9-326.9 356.6-326.9 196.6 0 356.6 146.6 356.6 326.9 0 16.4 13.3 29.7 29.7 29.7s29.7-13.3 29.7-29.7c0-170.6-119.8-315.4-285.2-366.5zM333.7 333.7c0-98.3 80-178.3 178.3-178.3s178.3 80 178.3 178.3S610.3 512 512 512s-178.3-80-178.3-178.3z"
                        fill="currentColor"
                      ></path>
                    </svg>
                    {state.isLogin ? '用户名' : '手机号/邮箱'}
                  </>
                }
                name="account"
                value={state.account}
                onChange={(e) => {
                  setState({
                    account: e,
                  });
                }}
                errorMeassage={state.accountError}
              />

              <FormItem
                label={
                  <>
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      fill="none"
                      viewBox="0 0 24 24"
                    >
                      <path
                        stroke="currentColor"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth="1.5"
                        d="M16.423 9.448V7.3a4.552 4.552 0 00-4.551-4.551 4.55 4.55 0 00-4.57 4.53v2.168"
                      ></path>
                      <path
                        stroke="currentColor"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth="1.5"
                        d="M15.683 21.25H8.042a3.792 3.792 0 01-3.792-3.792v-4.29a3.792 3.792 0 013.792-3.791h7.641a3.792 3.792 0 013.792 3.792v4.289a3.792 3.792 0 01-3.792 3.792z"
                        clipRule="evenodd"
                      ></path>
                      <path
                        stroke="currentColor"
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth="1.5"
                        d="M11.862 14.203v2.22"
                      ></path>
                    </svg>
                    密码
                  </>
                }
                name="password"
                value={state.password}
                onChange={(e) => {
                  setState({
                    password: e,
                  });
                }}
                type={'password'}
                errorMeassage={state.passwordError}
              />
            </div>
            <div className={styles.loginBtn}>
              <button
                disabled={state.loading}
                onClick={async () => {
                  const isValidate = validate(state.account, state.password);
                  if (!isValidate) {
                    return;
                  }
                  if (state.loading) return;
                  setState({
                    loading: true,
                  });
                  let res;
                  try {
                    if (state.isLogin) {
                      res = await login({
                        account: state.account,
                        password: state.password,
                      });
                    } else {
                      res = await register({
                        account: state.account,
                        password: state.password,
                        origin: document?.referrer?.split('?')[0],
                      });
                    }
                  } catch (e) {
                    setState({
                      loading: false,
                    });
                  }
                  setState({
                    loading: false,
                  });
                  if (res.code === 200) {
                    cookie.set('baijie_token', res.data?.access_token);
                    localStorage.setItem(
                      'user',
                      JSON.stringify({
                        account: state.account,
                        password: state.password,
                      }),
                    );
                    notification({
                      message: res.msg,
                      type: 'success',
                    });
                    if (state.isLogin) {
                      // const templates = await getResumes();
                      // if (templates.code === 200) {
                      //   setMyResumes(templates.data);
                      // }
                    }

                    if (needReload) {
                      window.location.reload();
                    } else {
                      if (pathname === '/content') {
                        let resume = await validResume();
                        if (resume.code === 200 && resume.data) {
                          Confirm({
                            title: '提示',
                            content: '您已创建过1份简历！是否去查看',
                            onOk() {
                              location.href = '/my/cv';
                            },
                          });
                        }
                      }
                    }
                    setShowLogin(false);
                    setIsLogin(true);
                  }
                }}
              >
                {state.loading ? <Loading /> : null}
                {state.isLogin ? '登录' : '注册'}
              </button>
            </div>
            <div className={styles.registerBtn}>
              <button
                disabled={state.loading}
                onClick={() => {
                  setState({
                    isLogin: !state.isLogin,
                  });
                }}
              >
                {!state.isLogin ? (
                  <div>
                    <span style={{ fontWeight: 'normal' }}>已有账号？</span>
                    <span>立即登录</span>
                  </div>
                ) : (
                  '创建账号'
                )}
              </button>
            </div>
          </div>
        </Mask>
      ) : null}
    </>
  );
};

export default Index;
